﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using LiveWebServiceBase;
using LiveWebServiceBase.ServiceUser;
using LiveWebServiceBase.ServiceUserSettings;

namespace LiveWebService.ELMS
{
    public class LiveELMS
    {
        #region Properties
        private string RedirectUrl;
        private string Uid;
        private string LastName;
        private string FirstName;
        private string Email;
        private List<string> Groups;
        private List<string> Errors;
        private bool IsSuccess;
        private string _token;
        private string _returnUrl;
        private string _liveID;
        private string _campus;
        private string _department;
        private string _loginUrl
        {
            get
            {
                if (!string.IsNullOrEmpty(_campus) || !string.IsNullOrEmpty(_elmsserver))
                    return Settings.ELMSVariables.loginUrl.Replace("%campus%", _campus).Replace("%server%", _elmsserver);
                else
                    throw new Exception("Attributes 'campus' and 'elmsurl' in service user XML setings file are empty or didn't exists.");
            }
        }
        private string _cgiConnectorUrl
        {
            get
            {
                if (!string.IsNullOrEmpty(_campus) || !string.IsNullOrEmpty(_elmsserver))
                    return Settings.ELMSVariables.cgiConnectorUrl.Replace("%campus%", _campus).Replace("%server%", _elmsserver);
                else
                    throw new Exception("Attributes 'campus' and 'elmsurl' in service user XML setings file are empty or didn't exists.");
            }
        }
        private string _defaultgroup;
        private string _elmsserver;
        #endregion

        public LiveELMS(User currentUser, string LiveID)
        {
            Organization orgItem = currentUser.GetOrganizationByLiveID(LiveID);

            _liveID = LiveID;
            _campus = orgItem.campus;
            _department = orgItem.department;
            _defaultgroup = orgItem.defaultgroup;
            _elmsserver = orgItem.elmsurl;

            Groups = new List<string>();
            Errors = new List<string>();
        }

        public string GetELMSRedirectString(String GroupName, String firstName, String lastName, String email)
        {
            if (string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(lastName) && string.IsNullOrEmpty(email))
                this.Uid = _liveID.Split('@')[0];
            else
                this.Uid = HttpUtility.UrlEncode(string.Format("{0} {1} ({2})", firstName, lastName, email));

            if (!string.IsNullOrEmpty(GroupName))
                this.Groups.Add(GroupName);

            this.FirstName = firstName;
            this.LastName = lastName;
            this.Email = email;

            this.Connect();

            if (this.IsSuccess)
                return this.RedirectUrl;
            else
                throw new Exception(string.Join(",", this.Errors.ToArray()));
        }

        private void Connect()
        {
            initializeSession();
            openSession();
        }

        private void initializeSession()
        {
            string RedirectUrl = string.Empty;
            WebRequest request;
            WebResponse responce;

            request = HttpWebRequest.Create(_loginUrl);
            request.Timeout = 50000;
            responce = request.GetResponse();
            NameValueCollection parameters = HttpUtility.ParseQueryString(responce.ResponseUri.Query.TrimStart("?".ToCharArray()));
            if (!string.IsNullOrEmpty(parameters["token"]) && !string.IsNullOrEmpty(parameters["token"]))
            {
                _returnUrl = parameters["return_url"];
                _token = parameters["token"];
            }

            request = null;

            responce.Close();
            responce = null;
        }

        private string openSession()
        {
            #region Required parameters
            if (object.Equals(null, _token) || object.Equals(string.Empty, _token))
            {
                throw new ArgumentException("token is not defined");
            }

            if (object.Equals(null, _returnUrl) || object.Equals(string.Empty, _returnUrl))
            {
                throw new ArgumentException("return_url is not defined");
            }

            if (object.Equals(null, Uid) || object.Equals(string.Empty, Uid))
            {
                throw new ArgumentException("uid is not defined");
            }

            if (object.Equals(0, Groups.Count))
            {
                if (string.IsNullOrEmpty(_defaultgroup))
                    throw new ArgumentException("No one group specified");
                else
                    Groups.Add(_defaultgroup);
            }

            if (object.Equals(null, _department) || object.Equals(string.Empty, _department))
            {
                throw new ArgumentException("department is not defined");
            }
            #endregion

            string queryString = string.Format("&uid={0}&groups={1}&token={2}&department={3}",
                                                Uid, string.Join(",", Groups.ToArray()), _token, _department);

            #region Optional parameters
            if (!object.Equals(string.Empty, LastName) && !object.Equals(null, LastName))
            {
                queryString += "&lname=" + LastName;
            }

            if (!object.Equals(string.Empty, FirstName) && !object.Equals(null, FirstName))
            {
                queryString += "&fname=" + FirstName;
            }

            if (!object.Equals(string.Empty, Email) && !object.Equals(null, Email))
            {
                queryString += "&email=" + Email;
            }
            #endregion

            Uri cgiConnectorUri = new Uri(_cgiConnectorUrl + queryString + string.Format("&return_url={0}", _returnUrl));
            WebRequest request;
            WebResponse responce;

            request = HttpWebRequest.Create(cgiConnectorUri);
            request.Timeout = 50000;
            responce = request.GetResponse();
            StreamReader sr = new StreamReader(responce.GetResponseStream());
            string responceBody = sr.ReadToEnd();

            sr.Close();
            sr = null;

            if (responceBody.Contains("0 Account"))
            {
                RedirectUrl = _returnUrl + queryString;
                IsSuccess = true;
            }
            else
            {
                Errors.Add(responceBody);
                System.Diagnostics.Debug.WriteLine(responceBody);
            }

            request = null;

            responce.Close();
            responce = null;

            return RedirectUrl;
        }
    }
}